<template>
  <div class="container">
    <el-dialog v-if="dialogVisible" :title="title"
      :visible.sync="dialogVisible" :before-close="handleCancel"
      :opened="openedFn()"
      center top="5vh"
      width="1200px"
      >
      <el-radio-group v-model="time"
      class="searchRight"
      @change="changeTime"
      style="margin-bottom: 20px;">
        <el-radio-button label="hours">近24小时</el-radio-button>
        <el-radio-button label="weeks">近一周</el-radio-button>
        <el-radio-button label="months">近一月</el-radio-button>
      </el-radio-group>

      <div class="describe" style="margin-bottom: 20px">
        设备编号:{{ rowData.deviceNumber}}, 设备类型：{{ typeName}}, &nbsp;地点：{{rowData.address}}
      </div>

      <!-- <div class="titleCss">
          <div class="tip-btn" v-for="item in tableHeaders"
          :key="item.paramName"
            >
            <div class="title">{{item.paramMemo}}</div>
            <span class="icon-question"
            @mouseenter="inputFn({'num':'1','data': item.paramMemo})"
            @mouseout="outputFn">?</span>
          </div>
          <p v-show="tipsShow" id="tipsDom" class="tipsDetail">{{anomaly}}异常值：1.2mg/m3 &lt;HCHO值</p> -->

          <!-- <div class="tip-btn"
            style="margin-left: -35px;">甲醛
            <span class="icon-question"
            @mouseenter="inputFn({'num':'2','data': '甲醛'})"
            @mouseout="outputFn"
            >?</span>
          </div>
          <p class="tip-btn" style="width: 94px; margin-right: 200px;">二氧化碳
            <span class="icon-question"
            @mouseenter="inputFn({'num':'3','data': '二氧化碳'})"
            @mouseout="outputFn"
            >?</span>
          </p> -->
        <!-- </div> -->
      <div class="charts" :width="DialogWidth">
        <!-- :id="oneChart" -->
            <!-- @mouseenter="inputFn({'num':'1','data': item.paramMemo})" -->
          <div class="tip-btn" v-for="(item,index) in checkHeaders"
            :key="item.paramName">
            <div class="title">
              <!-- <span class="title"></span> -->
              {{item.paramMemo}}
              <span
                class="icon-question"
                :id="'icon'+index"
                @mousemove="item.flag = true"
                @mouseleave="item.flag = false"
              >
                ?
                <div v-show="item.flag && item.badValue" :id="index" class="tipsDetail">{{ anomaly }}
                  指标说明：
                  <template v-if="item.badValue && item.bestValue">
                    <div>{{ item.paramMemo }}值 &lt; {{ item.bestValue }} 优</div>
                    <div>{{ item.bestValue }} &lt;= {{ item.paramMemo }}值 &lt; {{ item.badValue }} 良</div>
                    <div>{{ item.badValue }} &lt;= {{ item.paramMemo }}值 差</div>
                  </template>
                  <template v-else-if="item.badValue && !item.bestValue">
                    <!-- 目前只有硫化氢和氨气 -->
                    <div>{{ item.paramMemo }}值 &lt; {{ item.bestValue }} 正常</div>
                    <div>{{ item.badValue }} &lt;= {{ item.paramMemo }}值 差</div>
                  </template>
                </div>
                <p v-show="item.flag && !item.badValue" :id="index" class="tipsDetail">暂无指标</p>
              </span>
            </div>
            <div :id="item.paramName" :style="{width: autoWidth, height: autoHeight,'margin-right': '15px'}"></div>
          </div>
        <!-- <div id="twoChart" :style="{width: autoWidth, height: autoHeight}"></div>
        <div id="threeChart" :style="{width: autoWidth, height: autoHeight}"></div> -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getDeviceHistory } from '@/views/children/lot/js/deviceStatistics.js'
import { Message } from 'element-ui'
import { getOneOption } from '../js/chartOptions'
import { indicator, unitList } from '../js/indicatorConstant'
export default {
  components: {},
  props: {
    tableHeaders: {
      type: Array,
      required: true
    },
    autoDialogWidth: {
      type: Number,
      required: true
    },
    typeName: {
      type: String,
      required: false
    }
  },
  data () {
    return {
      dialogVisible: false,
      title: '历史数据',
      time: 'hours',
      checkHeaders: [],
      tipsShow: false,
      anomaly: '',
      autoWidth: '',
      autoHeight: '',
      DialogWidth: '',
      // options: '',
      rowData: {},
      optionData: {},
      optionsXList: [],
      optionsY: {}
    }
  },
  computed: {
  },
  watch: {
    dialogVisible: {
      handler: function (value) {
        if (!value) return
        this.$nextTick(() => {
          // this.initChart()
        })
      },
      deep: true
    }
  },
  created () {
    // this.autoWidth = this.$base.getDocumentWidth() / 5 + 'px'
    this.autoWidth = 400 + 'px'
    this.autoHeight = 300 + 'px'
    this.DialogWidth = this.autoDialogWidth > 2 ? 1200 + 'px' : this.autoDialogWidth * 400 + 'px'
  },
  methods: {
    async open (row) {
      this.rowData = row
      this.dialogVisible = true
      await this.getDeviceHistory(1)
      // this.optionData = {
      //   optionsXList: this.optionsXList
      // }
      this.initChart()
      // getOneOption(this.optionData)
    },

    // 监听dialog窗口的开启状态
    // 内部的任何dom的重绘都会重复执行opened
    openedFn () {},

    // 获取数据
    async getDeviceHistory (day) {
      try {
        let params = {
          day,
          deviceColumnModelList: this.tableHeaders,
          deviceId: this.rowData.deviceNumber,
          eqptId: this.rowData.eqptId
        }
        let res = await getDeviceHistory(params)

        if (res.code === 0) {
        // 24小时的要整理x轴数据
          if (day === 1) {
            // let tempArr = res.data.timeList.sort(this.compareNum)
            let tempArr = res.data.timeList
            let optionsXList = []
            // x轴数据整理
            tempArr.forEach(item => {
              if (+item < 10) {
                optionsXList.push('0' + item + ':00')
              } else {
                optionsXList.push(item + ':00')
              }
            })
            this.optionsXList = optionsXList
          } else {
          // 一周 或一月的 数据
            this.optionsXList = res.data.timeList
          }
          let tempYList = res.data.contentJsonList
          let yObj = {}
          let keyList = Object.keys(tempYList[0])
          keyList.forEach(key => {
            yObj[key] = []
            tempYList.forEach(item => {
              yObj[key].push(item[key] === null ? 0 : item[key])
            })
          })
          console.log('y轴', yObj, tempYList)
          this.optionsY = yObj
        } else {
          Message({
            type: 'error',
            message: res.msg
          })
        }
      } catch (e) {
        Message({
          type: 'error',
          message: '网络错误！'
        })
      }
    },
    // 排序
    // compareNum (x, y) {
    //   if (+x < +y) {
    //     return -1
    //   } else if (+x === +y) {
    //     return 0
    //   } else if (+x > +y) {
    //     return 1
    //   }
    // },
    // 更改时间
    async changeTime (val) {
      // hours 今天
      // weeks 近一周 获取七天前日期
      // months 近一月
      let day = val === 'hours' ? 1
        : val === 'weeks' ? 7 : 30
      await this.getDeviceHistory(day)
      this.initChart()
    },

    // 关闭弹窗
    handleCancel () {
      this.DialogWidth = ''
      this.$parent.visibleHistory = false
      this.dialogVisible = false
    },

    // 关闭弹窗
    handleClose () {
      this.handleCancel()
    },

    // 鼠标悬停事件 设置hover动态样式
    inputFn (item) {
      // e.stopPropagation()
      // this.tipsShow = true
      // let tipDom = document.getElementById('tipsDom')

      // tipDom.style.left = e.clientX - 150 + 'px'
      // tipDom.style.top = e.clientY + 'px'
      // if (this.autoDialogWidth > 2) {
      //   tipDom.style.left = e.clientX - 150 + 'px'
      //   tipDom.style.top = e.clientY - 20 + 'px'
      // }
    },

    // output鼠标离开事件
    outputFn (item) {
      item.flag = false
      this.tipsShow = false
    },

    // 初始化 echarts
    initChart () {
      let len = this.optionsXList.length
      this.tableHeaders.forEach(item => {
        const danger = indicator.find(n => n.indicator === item.paramName)?.bad
        let obj = {
          danger,
          interval: len > 7 ? 6 : 1,
          xData: this.optionsXList,
          yData: this.optionsY[item.paramName]
        }
        let options = getOneOption(obj)
        let chartName = item.paramName
        this.repetition(chartName, options)
      })
      // let oneOptions = getOneOption()
      // this.repetition('oneChart', oneOptions)

      // let twoOptions = getOneOption()
      // this.twoChart = echarts.init(document.getElementById('twoChart'))
      // twoOptions && this.twoChart.setOption(twoOptions)
      // this.repetition('twoChart', twoOptions)

      // let threeOptions = getOneOption()
      // this.threeChart = echarts.init(document.getElementById('threeChart'))
      // twoOptions && this.threeChart.setOption(threeOptions)
      // this.repetition('threeChart', threeOptions)
    },

    // 初始化
    repetition (name, option) {
      if (this[name] !== null &&
        this[name] !== '' &&
        this[name] !== undefined) {
        this[name].dispose()
      }
      this[name] = echarts.init(document.getElementById(name))
      option && this[name].setOption(option)
      // this[name].setOption(option, true)
    },
    format () {
      indicator.forEach(n => {
        unitList.forEach(u => {
          if (n.indicator === u.prop) {
            n.badValue = `${n.bad}${u.unit}`
            n.bestValue = `${n.best}${u.unit}`
          }
        })
      })
      this.checkHeaders = this.tableHeaders.map(item => {
        const isBadValue = indicator.find(n => n.indicator === item.paramName)?.badValue
        const isBestValue = indicator.find(n => n.indicator === item.paramName)?.bestValue
        return {
          ...item,
          flag: false,
          badValue: isBadValue || '',
          bestValue: isBestValue || ''
        }
      })
    }
  },
  mounted () {
    this.format()
  }
}
</script>
<style scoped lang="scss">
.charts {
  // width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}
.titleCss {
  display: flex;
  position: relative;
  justify-content: space-between;
}
.tipsCss {
  display: inline-block;
  width: 18px;
  height: 18px;
  border: 1px solid black;
  border-radius:50%;
  color: black;
  text-align: center;
}
.iconCss {
  background-color: #fff;
}
.title {
  position: relative;
  margin-right: 10px;
  display: flex;
  // float: left;
  height: 18px;
  line-height: 18px;
  .icon-question{
    color: #000;
  &:hover {
  // color: #ff0000;
    width: 18px;
    color: #ff0000;
    border: 1px solid #ff0000;
  }
  }
}
.tip-btn {
  // margin-left: 20px;
  // display: flex;
  // min-width: 70px;
  width: 370px;
  // justify-content: center;
  // align-items: center;
  // width: 70px;
  white-space: nowrap;
  font-size: 16px;
  cursor: pointer;
  span {
    font-size: 16px;
  }
}
.icon-question {
  // float: right;
  margin-left: 5px;
  width: 18px;
  height: 18px;
  font-size: 16px;
  border: 1px solid #333333;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}
.tipsDetail {
  // display: inline-block;
  // float: right;
  // position: absolute;
  // left: 0;
  // top: 0;
  // // right: 61%;
  // // bottom:0px;
  // height:40px;
  // width: 270px;
  // text-align: center;
  position: absolute;
  left: 30px;
  top: -10px;
  // line-height: 40px;
  padding: 10px 20px;
  font-size: 14px;
  background-color: #F2F2F2;
  color: #000;
  border-radius: 4px;
}
.tipsDetail2 {
  position: absolute;
  right: 29%;
  bottom:-36px;
  height:40px;
  width: 270px;
  // text-align: center;
  line-height: 40px;
  font-size: 14px;
  background-color: #F2F2F2;
}
// .el-dialog{
//   display: flex;
//   flex-direction: column;
//   margin:0 !important;
//   position:absolute;
//   top:50%;
//   left:50%;
//   transform:translate(-50%,-50%);
//   /*height:600px;*/
//   max-height:calc(100% - 30px);
//   max-width:calc(100% - 30px);
// }
// .container{
//   max-width: 1100px;
// }
</style>
